package com.lsl.rdf.api.impl;

import com.lsl.rdf.api.UserServiceRest;
import com.lsl.rdf.config.UserProperties;
import com.lsl.rdf.constant.*;
import com.lsl.rdf.do_.UserDo;
import com.lsl.rdf.result.BaseResult;
import com.lsl.rdf.service.UserService;
import com.lsl.rdf.service.UserSupport;
import com.lsl.rdf.utils.SnowflakeIdWorker;
import com.lsl.rdf.utils.bean.IBeanUtil;
import com.lsl.rdf.utils.encrypt.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static com.lsl.rdf.constant.enums.CommonConstants.USERNAME_PREFIX;

/**
 * Created by lsl on 2021/4/9.
 */
@Slf4j
@Service
public class UserServiceRestImpl implements UserServiceRest {

    @Autowired
    private UserService userService;
    @Autowired
    private UserSupport userSupport;
    @Autowired
    private UserProperties userProperties;
    @Autowired(required = false)
    private SnowflakeIdWorker snowflakeIdWorker;

    @Override
    public BaseResult<Boolean> userServiceRegisterRest(RegisterUserParam param) {
        String phone = param.getMobile();
        Integer phoneCount = userService.count(UserDo.builder().mobile(phone).build());
        if (Objects.nonNull(phoneCount) && phoneCount > 0) {
            log.warn("UserServiceRestImpl.userServiceRegisterRest 手机号已注册，不可重复注册！phone: {}", phone);
            return BaseResult.error("500001", "手机号已注册，不可重复注册");
        }

        String salt = RandomStringUtils.randomAlphanumeric(8);
        String password = Md5Util.md5(param.getPassword() + salt);

        UserDo createUserDo = UserDo.builder().username(USERNAME_PREFIX + phone)
                .mobile(phone).salt(salt).password(password).build();
        if (userProperties.isUseSnowflakeId()) {
            createUserDo.setId(snowflakeIdWorker.nextId());
        }
        userService.insert(createUserDo);
        return BaseResult.success();
    }

    @Override
    public BaseResult<TokenResult> userServiceLoginRest(LoginParam param) {
        UserDo userDo = userService.selectOne(UserDo.builder().mobile(param.getMobile()).build());

        boolean userExist = Objects.nonNull(userDo);
        if (!userExist) {
            return BaseResult.error("500002", "用户不存在");
        }
        boolean passwordPass = !Md5Util.validate(param.getPassword() + userDo.getSalt(), userDo.getPassword());
        if (passwordPass) {
            return BaseResult.error("500003", "手机号或密码错误");
        }
        return BaseResult.success(userSupport.createToken(userDo.getId()));
    }

    @Override
    public BaseResult<TokenResult> userServiceRefreshTokenRest() {
        return BaseResult.success(userSupport.refreshToken());
    }

    @Override
    public BaseResult<Boolean> userServiceLogoutRest() {
        return BaseResult.success(userSupport.removeToken());
    }

    @Override
    public BaseResult<UserResult> userServiceInfoRest() {
        UserDo userDo = userService.currentUser();
        if (Objects.isNull(userDo)) {
            return BaseResult.error("500004", "找不到用户信息");
        }
        UserResult userResult = IBeanUtil.copyInstance(userDo, UserResult::new);
        userResult.setPassword("[PROTECTED]");
        userResult.setRegisterDate(userDo.getCreateDate());
        return BaseResult.success(userResult);
    }

    @Override
    public BaseResult<Boolean> userServiceUpdateRest(UpdateUserParam param) {
        UserDo updateUser = IBeanUtil.copyInstance(param, UserDo::new);
        updateUser.setId(userService.currentUserId());
        return BaseResult.success(userService.updateById(updateUser));
    }
}
